package main

import (
	"log"

	//print "github.com/alexbrainman/printer"
	"unicode/utf8"

	"io/ioutil"
	"os"

	"github.com/axgle/mahonia"
)

func main() {

	log.Println("Hello, 世界", len("世界"), utf8.RuneCountInString("世界"))

	content := "\r\n  优诺 - \r\n"
	content += "\r\n  成飞大道 \r\n"
	content += "\r\n  12 斤   2018-08-31"
	enc := mahonia.NewEncoder("utf-8")
	content = enc.ConvertString(content)
	n := len(content)
	log.Println(n)
	log.Println(content)
	log.Println(Substr(content, 0, 15))
	log.Println(Substr(content, 15, n))
	log.Println("----------------------")
}

//截取字符串 start 起点下标 length 需要截取的长度
func Substr(str string, start int, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0

	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length

	if start > end {
		start, end = end, start
	}

	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}

	return string(rs[start:end])
}

//截取字符串 start 起点下标 end 终点下标(不包括)
func Substr2(str string, start int, end int) string {
	rs := []rune(str)
	length := len(rs)

	if start < 0 || start > length {
		panic("start is wrong")
	}

	if end < 0 || end > length {
		panic("end is wrong")
	}

	return string(rs[start:end])
}
